package com.ferris.redbook.service.impl;

import com.ferris.redbook.dto.response.PostResponse;
import com.ferris.redbook.entity.Post;
import com.ferris.redbook.mapper.PostMapper;
import com.ferris.redbook.service.PostService;
import com.ferris.redbook.util.FileUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class PostServiceImpl implements PostService {

    private final PostMapper postMapper;

    @Value("${app.upload.access-url-base}")
    private String accessUrlBase;

    @Override
    public List<PostResponse> getUserPosts(Long userId, int page, int limit) {
        // 计算偏移量
        int offset = (page - 1) * limit;

        // 查询用户帖子
        List<Post> posts = postMapper.selectUserPosts(userId, offset, limit);

        // 转换为响应对象
        return posts.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }

    @Override
    public long countUserPosts(Long userId) {
        return postMapper.countUserPosts(userId);
    }

    /**
     * 将Post实体转换为PostResponse
     */
    private PostResponse convertToResponse(Post post) {
        PostResponse response = new PostResponse();
        response.setId(post.getId());
        response.setTitle(post.getTitle());
        response.setContent(post.getContent());

        // 处理封面图URL
        if (post.getCoverImage() != null) {
            response.setCoverImage(accessUrlBase + "/" + post.getCoverImage());
        }

        response.setType(post.getType());
        response.setViewCount(post.getViewCount());
        response.setLikeCount(post.getLikeCount());
        response.setCommentCount(post.getCommentCount());
        response.setCollectCount(post.getCollectCount());
        response.setShareCount(post.getShareCount());
        response.setLocation(post.getLocation());
        response.setCreatedAt(post.getCreatedAt());

        // 获取帖子图片
        List<String> imageUrls = postMapper.selectPostImages(post.getId())
                .stream()
                .map(image -> accessUrlBase + "/" + image)
                .collect(Collectors.toList());
        response.setImages(imageUrls);

        // 获取用户信息
        // 这里假设您有UserMapper可以获取用户信息
        // User user = userMapper.selectById(post.getUserId());
        // response.setUser(convertToUserResponse(user));

        return response;
    }
}